package com.ncloud.uniformInterface.utils;

import com.ncloud.uniformInterface.exception.HttpException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;

/**
 * autho: shiqiang
 * date:  2015/12/3
 * 用途：
 */
public class HttpClientUtils {
    private int timeOut =0;
    /*text/plain
    * application/json*/
    private String requestType;

    public HttpClientUtils(){

    }
    public HttpClientUtils(int timeOut, String requestType){
        this.timeOut = timeOut;
        this.requestType = requestType;
    }

    public void setTimeOut(int timeOut) {
        this.timeOut = timeOut;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param serverUrl
     *            发送请求的 URL
     * @param data
     *            请求参数，请求参数默认json格式{"name":"张三","age":"20"}
     * @return 所代表远程资源的响应结果
     */
    @SuppressWarnings(value="unchecked")
    public  String post(String serverUrl, String data,Map<String,String>... maps){
        URL url =null;
        BufferedReader reader = null;
        OutputStreamWriter wr = null;
        StringBuilder responseBuilder = null;
        try {
            url = new URL(serverUrl);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            httpConnection.setDoOutput(true); // 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true
            httpConnection.setDoInput(true); // 从connection读入，默认是true
            httpConnection.setRequestMethod("POST");
            httpConnection.setUseCaches(false); // post请求不能使用缓存
            httpConnection.setConnectTimeout(this.timeOut <= 0 ? 5000 :timeOut);
            httpConnection.setReadTimeout(timeOut);
            httpConnection.setRequestProperty("Content-Type",requestType ==null ? "application/json":requestType);
            Arrays.stream(maps).forEach(map->map.forEach((key,value)-> {httpConnection.setRequestProperty(key,value);System.out.println(key+"="+value);}));
            //httpConnection.getHeaderFields().forEach((key,value)->System.out.println(key+"="+value));
            // 建立实际的连接，但是实际上get请求要在下一句的getInputStream()函数中才会真正发到服务器
            httpConnection.connect();
            wr = new OutputStreamWriter(httpConnection.getOutputStream());
            wr.write(data);
            wr.flush();
            //处理通讯异常
            if (httpConnection.getResponseCode() != 200) {
                throw new HttpException(httpConnection.getResponseCode()+"","Failed : HTTP error code : "
                        + httpConnection.getResponseCode());
            }
            reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            responseBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line).append("\n");
            }
            httpConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (wr != null) {
                try {
                    wr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return responseBuilder.toString();
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     *
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    @SuppressWarnings(value="unchecked")
    public String get(String url) throws Exception {
        URL localURL = new URL(url);
        HttpURLConnection httpURLConnection =(HttpURLConnection) localURL.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setConnectTimeout(this.timeOut <= 0 ? 5000 :timeOut);
        httpURLConnection.setReadTimeout(timeOut);
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        // 建立实际的连接
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() != 200) {
            throw new HttpException(httpURLConnection.getResponseCode()+"","Failed : HTTP error code : "
                    + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            httpURLConnection.disconnect(); // 断开连接
        } finally {
            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }
      // JSONObject response = JSONObject.parseObject(resultBuffer.toString());
        return resultBuffer.toString();
    }
}
